<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
    <div class="personal-data-container">
      <div class="profile-picture">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarChange"
        >
          <img v-if="profilePicture" :src="profilePicture" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <div class="user-details">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input
            type="number"
            v-model.number="form.age"
            :min="1"
            :max="1000"
            placeholder="请输入年龄"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div class="submit-button">
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="openDialog">修改密码</el-button>
      </div>
    </div>
  </el-form>

  <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
    <div class="dialog-content">
      <el-form
        :model="formPassord"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="auto"
        label-position="top"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="formPassord.oldPassword"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="formPassord.newPassword"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="formPassord.confirmPassword"
            type="password"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElForm, ElFormItem } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/model/user";

const userStore = useUserStore();
const profilePicture = ref("");
const avatarFile = ref(null);
const dialogFormVisible = ref(false);

const form = reactive({
  name: userStore.userInfo.name,
  gender: userStore.userInfo.gender,
  age: userStore.userInfo.age,
  phone: userStore.userInfo.phone,
});

const formPassord = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const rules = reactive({
  name: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/,
      message: "不能包含特殊字符",
      trigger: "blur",
    },
  ],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 1000,
      message: "年龄必须在 1 到 1000 岁之间",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

const passwordRules = reactive({
  oldPassword: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 6 到 16 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 6 到 16 个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== formPassord.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
    },
  ],
});

const openDialog = () => {
  dialogFormVisible.value = true;
};

const handleAvatarChange = (file) => {
  const isJPGorPNG =
    file.raw.type === "image/jpeg" || file.raw.type === "image/png";
  const isLt2M = file.raw.size / 1024 / 1024 < 2;

  if (!isJPGorPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  if (isJPGorPNG && isLt2M) {
    const reader = new FileReader();
    reader.onload = (e) => {
      profilePicture.value = e.target.result;
    };
    reader.readAsDataURL(file.raw);
    avatarFile.value = file.raw;
  }
};

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      console.log("提交的信息:", {
        name: form.name,
        gender: form.gender,
        age: form.age,
        phone: form.phone,
        avatar: avatarFile.value,
      });
      ElMessage.success("信息提交成功");
    } else {
      console.log("验证失败!");
      return false;
    }
  });
};

const passwordFormRef = ref(null);

const submitPasswordForm = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log("提交的密码信息:", {
        oldPassword: formPassord.oldPassword,
        newPassword: formPassord.newPassword,
        confirmPassword: formPassord.confirmPassword,
      });
      const res = await userStore.updateUserPasswordById(
        userStore.userInfo.id,
        formPassord.oldPassword,
        formPassord.newPassword
      );
      if (res) {
        formPassord.oldPassword = "";
        formPassord.newPassword = "";
        formPassord.confirmPassword = "";
        dialogFormVisible.value = false;
        ElMessage.success("密码修改成功");
      }
    } else {
      console.log("密码验证失败!");
      return false;
    }
  });
};

const formRef = ref(null);
</script>

<style scoped>
.personal-data-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
}

.profile-picture {
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.user-details {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 400px;
}

.detail {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  width: 80px;
}

.el-input {
  width: 100%;
}

.submit-button {
  margin-top: 20px;
}

.dialog-footer {
  text-align: center;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
